<?php
/**
 * 全局函数库
 */

require_once __DIR__ . '/config.php';

/**
 * 数据库连接
 */
function getDB() {
    static $pdo = null;
    
    if ($pdo === null) {
        try {
            $dsn = 'mysql:host=' . DB_HOST . ';port=' . DB_PORT . ';dbname=' . DB_NAME . ';charset=utf8mb4';
            $pdo = new PDO($dsn, DB_USERNAME, DB_PASSWORD);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            die('数据库连接失败: ' . $e->getMessage());
        }
    }
    
    return $pdo;
}

/**
 * 密码加密
 */
function passwordHash($password) {
    return password_hash($password, PASSWORD_BCRYPT);
}

/**
 * 验证密码
 */
function passwordVerify($password, $hash) {
    return password_verify($password, $hash);
}

/**
 * 生成随机字符串
 */
function generateRandomString($length = 10) {
    return bin2hex(random_bytes($length / 2));
}




/**
 * 文件上传（带图片压缩功能）
 */
function uploadFile($file, $type = 'image') {
    if (!isset($file) || $file['error'] !== UPLOAD_ERR_OK) {
        return ['success' => false, 'message' => '文件上传失败'];
    }
    
    // 检查文件类型 - 扩展支持的图片格式
    $allowedTypes = [
        'image' => ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp', 'image/tiff'],
        'order_screenshot' => ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp', 'image/tiff'],
        'qr_code' => ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp', 'image/tiff'],
        'settlement_screenshot' => ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp', 'image/tiff'],
        'file' => ['application/pdf', 'text/plain', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
    ];
    
    $fileType = $file['type'];
    $isValidType = false;
    
    if (isset($allowedTypes[$type])) {
        $isValidType = in_array($fileType, $allowedTypes[$type]);
    }
    
    // 如果按类型检查失败，尝试通过文件扩展名检查
    if (!$isValidType) {
        $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $allowedExtensions = [
            'image' => ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'tiff'],
            'order_screenshot' => ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'tiff'],
            'qr_code' => ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'tiff'],
            'settlement_screenshot' => ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'tiff'],
            'file' => ['pdf', 'txt', 'doc', 'docx']
        ];
        
        if (isset($allowedExtensions[$type])) {
            $isValidType = in_array($fileExtension, $allowedExtensions[$type]);
        }
    }
    
    if (!$isValidType) {
        return ['success' => false, 'message' => '不支持的文件类型: ' . $fileType];
    }
    
    // 检查文件大小 (最大5MB)
    if ($file['size'] > 15 * 1024 * 1024) {
        return ['success' => false, 'message' => '文件大小不能超过5MB'];
    }
    
    // 生成文件名
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = generateRandomString(16) . '.' . $extension;
    
    // 确定上传目录
    $uploadDir = UPLOAD_PATH;
    switch ($type) {
        case 'order_screenshot':
            $uploadDir .= 'orders/';
            break;
        case 'qr_code':
            $uploadDir .= 'qrcodes/';
            break;
        case 'settlement_screenshot':
            $uploadDir .= 'settlements/';
            break;
        default:
            $uploadDir .= 'images/';
    }
    
    // 确保目录存在
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
    
    $uploadPath = $uploadDir . $filename;
    
    if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
        // 如果是图片类型，进行压缩
        $isImageType = in_array($type, ['image', 'order_screenshot', 'qr_code', 'settlement_screenshot']);
        if ($isImageType && isImageFile($file['type'], $extension)) {
            $compressionResult = compressImage($uploadPath, $uploadPath, [
                'max_width' => 1200,      // 最大宽度
                'max_height' => 1200,     // 最大高度
                'quality' => 80,          // 图片质量 (0-100)
                'max_file_size' => 500 * 1024 // 目标最大文件大小 500KB
            ]);
            
            if (!$compressionResult['success']) {
                // 压缩失败，可以记录日志，但不上传失败
                error_log('图片压缩失败: ' . $compressionResult['message']);
            }
        }
        
        return [
            'success' => true,
            'filename' => $filename,
            'path' => $uploadPath,
            'url' => str_replace(UPLOAD_PATH, UPLOAD_URL, $uploadPath)
        ];
    }
    
    return ['success' => false, 'message' => '文件保存失败'];
}

/**
 * 处理多文件上传
 */
function uploadMultipleFiles($files, $type = 'image') {
    $results = [];
    
    if (!isset($files) || empty($files['name'][0])) {
        return $results;
    }
    
    foreach ($files['tmp_name'] as $key => $tmp_name) {
        if ($files['error'][$key] === UPLOAD_ERR_OK) {
            $file = [
                'name' => $files['name'][$key],
                'type' => $files['type'][$key],
                'tmp_name' => $tmp_name,
                'error' => $files['error'][$key],
                'size' => $files['size'][$key]
            ];
            
            $uploadResult = uploadFile($file, $type);
            if ($uploadResult['success']) {
                $results[] = [
                    'filename' => $uploadResult['filename'],
                    'url' => $uploadResult['url'],
                    'original_name' => $file['name']
                ];
            }
        }
    }
    
    return $results;
}

/**
 * 检查是否为图片文件
 */
function isImageFile($mimeType, $extension) {
    $imageMimeTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp'];
    $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
    
    return in_array($mimeType, $imageMimeTypes) || in_array($extension, $imageExtensions);
}

/**
 * 图片压缩函数
 */
function compressImage($sourcePath, $destinationPath, $options = []) {
    // 默认配置
    $defaultOptions = [
        'max_width' => 1200,
        'max_height' => 1200,
        'quality' => 80,
        'max_file_size' => 500 * 1024 // 500KB
    ];
    
    $options = array_merge($defaultOptions, $options);
    
    // 获取图片信息
    $imageInfo = getimagesize($sourcePath);
    if (!$imageInfo) {
        return ['success' => false, 'message' => '无法读取图片信息'];
    }
    
    $mimeType = $imageInfo['mime'];
    $originalWidth = $imageInfo[0];
    $originalHeight = $imageInfo[1];
    
    // 计算新的尺寸
    list($newWidth, $newHeight) = calculateNewDimensions(
        $originalWidth, 
        $originalHeight, 
        $options['max_width'], 
        $options['max_height']
    );
    
    // 创建图片资源
    $sourceImage = createImageFromFile($sourcePath, $mimeType);
    if (!$sourceImage) {
        return ['success' => false, 'message' => '不支持的图片格式'];
    }
    
    // 创建新图片
    $newImage = imagecreatetruecolor($newWidth, $newHeight);
    
    // 处理PNG和WEBP的透明背景
    if ($mimeType === 'image/png' || $mimeType === 'image/webp') {
        imagealphablending($newImage, false);
        imagesavealpha($newImage, true);
        $transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
        imagefilledrectangle($newImage, 0, 0, $newWidth, $newHeight, $transparent);
    } else {
        // 为JPEG等格式创建白色背景
        $white = imagecolorallocate($newImage, 255, 255, 255);
        imagefill($newImage, 0, 0, $white);
    }
    
    // 调整图片大小
    imagecopyresampled($newImage, $sourceImage, 0, 0, 0, 0, 
        $newWidth, $newHeight, $originalWidth, $originalHeight);
    
    // 保存图片
    $saveResult = saveImage($newImage, $destinationPath, $mimeType, $options['quality']);
    
    // 释放内存
    imagedestroy($sourceImage);
    imagedestroy($newImage);
    
    if (!$saveResult) {
        return ['success' => false, 'message' => '图片保存失败'];
    }
    
    // 检查文件大小，如果仍然过大，进一步压缩质量
    $fileSize = filesize($destinationPath);
    if ($fileSize > $options['max_file_size']) {
        return furtherCompressImage($destinationPath, $destinationPath, $options);
    }
    
    return ['success' => true, 'message' => '图片压缩成功'];
}

/**
 * 计算新尺寸，保持宽高比
 */
function calculateNewDimensions($originalWidth, $originalHeight, $maxWidth, $maxHeight) {
    if ($originalWidth <= $maxWidth && $originalHeight <= $maxHeight) {
        return [$originalWidth, $originalHeight];
    }
    
    $ratio = $originalWidth / $originalHeight;
    
    if ($maxWidth / $maxHeight > $ratio) {
        $newWidth = $maxHeight * $ratio;
        $newHeight = $maxHeight;
    } else {
        $newWidth = $maxWidth;
        $newHeight = $maxWidth / $ratio;
    }
    
    return [round($newWidth), round($newHeight)];
}

/**
 * 从文件创建图片资源
 */
function createImageFromFile($path, $mimeType) {
    switch ($mimeType) {
        case 'image/jpeg':
            return imagecreatefromjpeg($path);
        case 'image/png':
            return imagecreatefrompng($path);
        case 'image/gif':
            return imagecreatefromgif($path);
        case 'image/webp':
            return imagecreatefromwebp($path);
        case 'image/bmp':
            return imagecreatefrombmp($path);
        default:
            return null;
    }
}

/**
 * 保存图片
 */
function saveImage($image, $path, $mimeType, $quality) {
    switch ($mimeType) {
        case 'image/jpeg':
            return imagejpeg($image, $path, $quality);
        case 'image/png':
            // PNG质量参数是0-9，需要转换
            $pngQuality = 9 - round(($quality / 100) * 9);
            return imagepng($image, $path, $pngQuality);
        case 'image/gif':
            return imagegif($image, $path);
        case 'image/webp':
            return imagewebp($image, $path, $quality);
        case 'image/bmp':
            return imagebmp($image, $path);
        default:
            return false;
    }
}

/**
 * 进一步压缩图片（当第一次压缩后文件仍然过大时使用）
 */
function furtherCompressImage($sourcePath, $destinationPath, $options) {
    $quality = $options['quality'];
    $maxFileSize = $options['max_file_size'];
    
    // 逐步降低质量，直到文件大小符合要求或质量降到最低
    while ($quality > 20) {
        $quality -= 10;
        
        $imageInfo = getimagesize($sourcePath);
        $mimeType = $imageInfo['mime'];
        
        $sourceImage = createImageFromFile($sourcePath, $mimeType);
        if (!$sourceImage) break;
        
        saveImage($sourceImage, $destinationPath, $mimeType, $quality);
        imagedestroy($sourceImage);
        
        if (filesize($destinationPath) <= $maxFileSize) {
            return ['success' => true, 'message' => '图片压缩成功'];
        }
    }
    
    return ['success' => false, 'message' => '图片压缩后仍然过大'];
}
/**
 * 删除文件
 */
function deleteFile($filename, $type = 'image') {
    if (empty($filename)) {
        return false;
    }
    
    $uploadDir = UPLOAD_PATH;
    switch ($type) {
        case 'order_screenshot':
            $uploadDir .= 'orders/';
            break;
        case 'qr_code':
            $uploadDir .= 'qrcodes/';
            break;
        case 'settlement_screenshot':
            $uploadDir .= 'settlements/';
            break;
        default:
            $uploadDir .= 'images/';
    }
    
    $filePath = $uploadDir . $filename;
    if (file_exists($filePath)) {
        return unlink($filePath);
    }
    
    return false;
}

/**
 * 获取用户信息
 */
function getUserInfo($userId = null) {
    if ($userId === null && isset($_SESSION['user_id'])) {
        $userId = $_SESSION['user_id'];
    }
    
    if (!$userId) {
        return null;
    }
    
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM users WHERE id = ? AND status = 1");
    $stmt->execute([$userId]);
    
    return $stmt->fetch();
}


/**
 * 获取网站信息（带缓存）
 */
function settings() {
    static $cached_settings = null;
    
    if ($cached_settings === null) {
        $db = getDB();
        $cached_settings = [];
        $stmt = $db->query("SELECT * FROM settings");
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($rows as $row) {
            $cached_settings[$row['key_name']] = $row['key_value'];
        }
    }
    
    return $cached_settings;
}
/**
 * 检查是否登录
 */
// 在 functions.php 的 isLoggedIn() 函数前添加自动登录检查
function checkAutoLogin() {
    // 如果会话中已登录，直接返回
    if (isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])) {
        return true;
    }
    
    // 检查记住我cookie
    if (isset($_COOKIE['remember_token']) && isset($_COOKIE['user_id'])) {
        $rememberToken = $_COOKIE['remember_token'];
        $userId = intval($_COOKIE['user_id']);
        
        if ($userId > 0 && !empty($rememberToken)) {
            $db = getDB();
            $stmt = $db->prepare("SELECT * FROM users WHERE id = ? AND remember_token = ? AND token_expire > NOW() AND status = 1");
            $stmt->execute([$userId, $rememberToken]);
            $user = $stmt->fetch();
            
            if ($user) {
                // 自动登录成功
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['is_admin'] = $user['is_admin'];
                
                // 更新token有效期（滑动过期时间）
                $newExpireTime = time() + (30 * 24 * 60 * 60);
                $stmt = $db->prepare("UPDATE users SET token_expire = ? WHERE id = ?");
                $stmt->execute([date('Y-m-d H:i:s', $newExpireTime), $user['id']]);
                
                setcookie('remember_token', $rememberToken, $newExpireTime, '/', '', false, true);
                setcookie('user_id', $user['id'], $newExpireTime, '/', '', false, true);
                
                return true;
            } else {
                // token无效，清除cookie
                setcookie('remember_token', '', time() - 3600, '/');
                setcookie('user_id', '', time() - 3600, '/');
            }
        }
    }
    
    return false;
}

// 修改 isLoggedIn 函数
function isLoggedIn() {
    // 先检查自动登录
    if (checkAutoLogin()) {
        return true;
    }
    
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

/**
 * 检查是否是管理员
 */
function isAdmin() {
    if (!isLoggedIn()) {
        return false;
    }
    
    $user = getUserInfo();
    return $user && $user['is_admin'];
}

/**
 * 重定向
 */
function redirect($url, $message = '', $type = 'success') {
    if ($message) {
        $_SESSION['flash_message'] = [
            'type' => $type,
            'message' => $message
        ];
    }
    header('Location: ' . $url);
    exit;
}

/**
 * 显示闪存消息
 */
function showFlashMessage() {
    if (isset($_SESSION['flash_message'])) {
        $message = $_SESSION['flash_message'];
        echo '<div class="alert alert-' . htmlspecialchars($message['type']) . ' alert-dismissible fade show" role="alert">';
        echo htmlspecialchars($message['message']);
        echo '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
        echo '</div>';
        unset($_SESSION['flash_message']);
    }
}

/**
 * 格式化时间
 */
function formatTime($timestamp) {
    return date('Y-m-d H:i:s', strtotime($timestamp));
}

/**
 * 格式化金额
 */
function formatAmount($amount) {
    return '¥' . number_format($amount, 2);
}

/**
 * 获取订单状态文本（兼容旧版本）
 */
function getOrderStatusText($status) {
    $statusMap = [
        'pending' => '未结算',
        'settled' => '已结算',
        'refunded' => '已退还'
    ];
    
    return $statusMap[$status] ?? '未知状态';
}

/**
 * 获取订单状态类（兼容旧版本）
 */
function getOrderStatusClass($status) {
    $classMap = [
        'pending' => 'warning',
        'settled' => 'success',
        'refunded' => 'danger'
    ];
    
    return $classMap[$status] ?? 'secondary';
}

/**
 * 获取订单登记状态文本
 */
function getOrderRegistrationText($isRegistered) {
    return $isRegistered ? '已登记' : '未登记';
}

/**
 * 获取订单登记状态类
 */
function getOrderRegistrationClass($isRegistered) {
    return $isRegistered ? 'success' : 'warning';
}

/**
 * 获取订单结算类型文本
 */
function getSettlementTypeText($settlementType) {
    $typeMap = [
        'none' => '未结算',
        'principal' => '结本金',
        'principal_commission' => '结本金+佣金'
    ];
    
    return $typeMap[$settlementType] ?? '未结算';
}


/**
 * 获取订单结算类型类
 */
function getSettlementTypeClass($settlementType) {
    $classMap = [
        'none' => 'secondary',
        'principal' => 'info',
        'principal_commission' => 'primary'
    ];
    
    return $classMap[$settlementType] ?? 'secondary';
}

/**
 * 获取订单退还状态文本
 */
function getOrderReturnText($isReturned) {
    return $isReturned ? '已退还' : '未退还';
}

/**
 * 获取订单退还状态类
 */
function getOrderReturnClass($isReturned) {
    return $isReturned ? 'danger' : 'secondary';
}

/**
 * 获取订单签收状态文本
 */
function getOrderSignText($isSigned) {
    return $isSigned ? '已签收' : '未签收';
}

/**
 * 获取订单签收状态类
 */
function getOrderSignClass($isSigned) {
    return $isSigned ? 'success' : 'warning';
}

/**
 * 获取订单完整状态显示
 */
function getOrderFullStatus($order) {
    $status = [];
    
    // 登记状态
    $status['registration'] = [
        'text' => getOrderRegistrationText($order['is_registered']),
        'class' => getOrderRegistrationClass($order['is_registered'])
    ];
    
    // 结算类型
    $status['settlement'] = [
        'text' => getSettlementTypeText($order['settlement_type']),
        'class' => getSettlementTypeClass($order['settlement_type'])
    ];
    
    // 退还状态
    $status['return'] = [
        'text' => getOrderReturnText($order['is_returned']),
        'class' => getOrderReturnClass($order['is_returned'])
    ];
    
    // 签收状态
    $status['sign'] = [
        'text' => getOrderSignText($order['is_signed']),
        'class' => getOrderSignClass($order['is_signed'])
    ];
    
    return $status;
}


/**
 * 获取订单操作记录
 */
function getOrderOperations($orderId) {
    $db = getDB();
    $stmt = $db->prepare("SELECT oo.*, u.username as admin_name FROM order_operations oo LEFT JOIN users u ON oo.admin_id = u.id WHERE oo.order_id = ? ORDER BY oo.created_at DESC");
    $stmt->execute([$orderId]);
    return $stmt->fetchAll();
}

/**
 * 获取订单操作类型文本
 */
function getOperationTypeText($type) {
    $typeMap = [
        'register' => '登记',
        'settle_principal' => '结本金',
        'settle_commission' => '结本金+佣金',
        'return' => '退还',
        'update_info' => '修改信息',
        'mark_refunded' => '标记回款',
        'cancel_refund' => '取消回款'
    ];
    
    return $typeMap[$type] ?? $type;
}

/**
 * 获取订单操作类型类
 */
function getOperationTypeClass($type) {
    $classMap = [
        'register' => 'info',
        'settle_principal' => 'primary',
        'settle_commission' => 'success',
        'return' => 'danger',
        'update_info' => 'secondary',
        'mark_refunded' => 'success',
        'cancel_refund' => 'warning'
    ];
    
    return $classMap[$type] ?? 'secondary';
}

/**
 * 分页
 */
function paginate($sql, $params = [], $page = 1, $perPage = 20) {
    $db = getDB();
    
    // 获取总记录数
    $countSql = preg_replace('/SELECT.*?FROM/si', 'SELECT COUNT(*) as total FROM', $sql);
    $countStmt = $db->prepare($countSql);
    $countStmt->execute($params);
    $total = $countStmt->fetch()['total'];
    
    // 计算分页
    $totalPages = ceil($total / $perPage);
    $page = max(1, min($page, $totalPages ?: 1));
    $offset = ($page - 1) * $perPage;
    
    // 获取数据
    $dataSql = $sql . " LIMIT $offset, $perPage";
    $dataStmt = $db->prepare($dataSql);
    $dataStmt->execute($params);
    $data = $dataStmt->fetchAll();
    
    return [
        'data' => $data,
        'total' => $total,
        'page' => $page,
        'perPage' => $perPage,
        'totalPages' => $totalPages,
        'hasMore' => $page < $totalPages
    ];
}

/**
 * 获取配置选项
 */
function getConfigOptions($type) {
    $db = getDB();
    $stmt = $db->prepare("SELECT option_value, option_label FROM config_options WHERE config_type = ? AND is_active = 1 ORDER BY sort_order ASC, option_label ASC");
    $stmt->execute([$type]);
    return $stmt->fetchAll();
}

/**
 * 获取公告列表
 */
function getAnnouncements($activeOnly = true) {
    $db = getDB();
    $sql = "SELECT * FROM announcements";
    if ($activeOnly) {
        $sql .= " WHERE is_active = 1";
    }
    $sql .= " ORDER BY priority DESC, created_at DESC";
    
    $stmt = $db->query($sql);
    return $stmt->fetchAll();
}

/**
 * 获取付款方式文本
 */
function getPaymentMethodText($method) {
    $methodMap = [
        'owner_paid' => '自己付款',
        'group_paid' => '群主垫付'
    ];
    
    return $methodMap[$method] ?? '未知方式';
}

/**
 * 获取配置选项标签
 */
function getConfigOptionLabel($type, $value) {
    $db = getDB();
    $stmt = $db->prepare("SELECT option_label FROM config_options WHERE config_type = ? AND option_value = ? AND is_active = 1");
    $stmt->execute([$type, $value]);
    $result = $stmt->fetch();
    
    return $result ? $result['option_label'] : $value;
}

// 在 functions.php 文件中添加以下函数

/**
 * 获取用户的待结算记录
 */
function getUserPendingSettlement($userId) {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM settlements WHERE user_id = ? AND status = 'pending'");
    $stmt->execute([$userId]);
    return $stmt->fetch();
}

/**
 * 创建用户结算记录
 */
function createUserSettlement($userId, $settlementType, $totalAmount, $orderIds, $adminId) {
    $db = getDB();
    $stmt = $db->prepare("INSERT INTO settlements (user_id, settlement_type, total_amount, order_ids, admin_id, status) VALUES (?, ?, ?, ?, ?, 'pending')");
    return $stmt->execute([$userId, $settlementType, $totalAmount, json_encode($orderIds), $adminId]);
}

/**
 * 更新用户结算记录
 */
function updateUserSettlement($settlementId, $totalAmount, $orderIds) {
    $db = getDB();
    $stmt = $db->prepare("UPDATE settlements SET total_amount = ?, order_ids = ?, updated_at = NOW() WHERE id = ?");
    return $stmt->execute([$totalAmount, json_encode($orderIds), $settlementId]);
}

/**
 * 获取结算记录的订单详情
 */
function getSettlementOrders($settlementId) {
    $db = getDB();
    $stmt = $db->prepare("SELECT order_ids FROM settlements WHERE id = ?");
    $stmt->execute([$settlementId]);
    $settlement = $stmt->fetch();
    
    if (!$settlement || empty($settlement['order_ids'])) {
        return [];
    }
    
    $orderIds = json_decode($settlement['order_ids'], true);
    if (empty($orderIds)) {
        return [];
    }
    
    $placeholders = str_repeat('?,', count($orderIds) - 1) . '?';
    $stmt = $db->prepare("SELECT o.*, u.username, u.phone FROM orders o LEFT JOIN users u ON o.user_id = u.id WHERE o.id IN ($placeholders)");
    $stmt->execute($orderIds);
    return $stmt->fetchAll();
}

/**
 * 发送结算完成推送通知
 */
function sendSettlementNotification($userId, $settlementId, $orderDetails) {
    $db = getDB();
    $stmt = $db->prepare("SELECT u.pushplus_enabled, u.pushplus_token, s.total_amount, s.settlement_type FROM users u LEFT JOIN settlements s ON s.id = ? WHERE u.id = ?");
    $stmt->execute([$settlementId, $userId]);
    $data = $stmt->fetch();
    
    if (!$data || !$data['pushplus_enabled'] || empty($data['pushplus_token'])) {
        return false;
    }
    
    $message = "您的结算申请已完成\n";
    $message .= "结算类型：" . ($data['settlement_type'] == 'commission' ? '本金' : '本金+佣金') . "\n";
    $message .= "结算金额：¥" . number_format($data['total_amount'], 2) . "\n";
    $message .= "结算时间：" . date('Y-m-d H:i:s') . "\n\n";
    
    if (!empty($orderDetails)) {
        $message .= "关联订单详情：\n";
        foreach ($orderDetails as $index => $order) {
            $message .= ($index + 1) . ". " . $order['product_name'] . " - ¥" . number_format($order['settlement_amount'] ?? $order['order_amount'], 2) . "\n";
        }
    }
    
    try {
        $pushData = [
            'token' => $data['pushplus_token'],
            'title' => '结算完成通知',
            'content' => $message,
            'template' => 'txt'
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, PUSHPLUS_API_URL);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($pushData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        $result = curl_exec($ch);
        curl_close($ch);
        
        return $result !== false;
    } catch (Exception $e) {
        error_log("PushPlus推送失败: " . $e->getMessage());
        return false;
    }
}

/**
 * 处理订单结算到待结账单
 */
function processOrderSettlement($orderId, $settlementType, $settlementAmount, $settlementInfo, $adminId) {
    $db = getDB();
    
    // 获取订单信息
    $stmt = $db->prepare("SELECT user_id, order_amount FROM orders WHERE id = ?");
    $stmt->execute([$orderId]);
    $order = $stmt->fetch();
    
    if (!$order) {
        return false;
    }
    
    $userId = $order['user_id'];
    
    // 计算结算金额
    $finalSettlementAmount = $settlementAmount;
    if (empty($finalSettlementAmount)) {
        if ($settlementType == 'commission') {
            $finalSettlementAmount = $order['order_amount'] * 0.1; // 10%佣金示例
        } else {
            $finalSettlementAmount = $order['order_amount'];
        }
    }
    
    // 检查是否已存在待结算记录
    $pendingSettlement = getUserPendingSettlement($userId);
    
    if ($pendingSettlement) {
        // 更新现有记录
        $existingOrderIds = json_decode($pendingSettlement['order_ids'], true) ?: [];
        $existingOrderIds[] = $orderId;
        $newTotalAmount = $pendingSettlement['total_amount'] + $finalSettlementAmount;
        
        return updateUserSettlement($pendingSettlement['id'], $newTotalAmount, $existingOrderIds);
    } else {
        // 创建新记录
        return createUserSettlement($userId, $settlementType, $finalSettlementAmount, [$orderId], $adminId);
    }
}



// 在 functions.php 中添加以下函数

/**
 * 调整颜色亮度
 */
function adjustBrightness($hex, $steps) {
    $steps = max(-255, min(255, $steps));
    $hex = str_replace('#', '', $hex);
    
    if (strlen($hex) == 3) {
        $hex = str_repeat(substr($hex,0,1), 2).str_repeat(substr($hex,1,1), 2).str_repeat(substr($hex,2,1), 2);
    }
    
    $r = hexdec(substr($hex,0,2));
    $g = hexdec(substr($hex,2,2));
    $b = hexdec(substr($hex,4,2));
    
    $r = max(0,min(255,$r + $steps));
    $g = max(0,min(255,$g + $steps));  
    $b = max(0,min(255,$b + $steps));
    
    $r_hex = str_pad(dechex($r), 2, '0', STR_PAD_LEFT);
    $g_hex = str_pad(dechex($g), 2, '0', STR_PAD_LEFT);
    $b_hex = str_pad(dechex($b), 2, '0', STR_PAD_LEFT);
    
    return '#'.$r_hex.$g_hex.$b_hex;
}

/**
 * 十六进制颜色转RGBA
 */
function hex2rgba($hex, $alpha = 1) {
    $hex = str_replace('#', '', $hex);
    
    if (strlen($hex) == 3) {
        $r = hexdec(str_repeat(substr($hex,0,1),2));
        $g = hexdec(str_repeat(substr($hex,1,1),2));
        $b = hexdec(str_repeat(substr($hex,2,1),2));
    } else {
        $r = hexdec(substr($hex,0,2));
        $g = hexdec(substr($hex,2,2));
        $b = hexdec(substr($hex,4,2));
    }
    
    return "rgba($r, $g, $b, $alpha)";
}

/**
 * 更新用户主题设置
 */
function updateUserTheme($themeName, $themeColor) {
    $_SESSION['theme_name'] = $themeName;
    $_SESSION['theme_color'] = $themeColor;
    
    // 如果用户已登录，保存到数据库
    if (isLoggedIn()) {
        $db = getDB();
        $stmt = $db->prepare("UPDATE users SET theme_name = ?, theme_color = ? WHERE id = ?");
        $stmt->execute([$themeName, $themeColor, $_SESSION['user_id']]);
    }
}

/**
 * 初始化用户主题设置
 */
function initUserTheme() {
    if (isLoggedIn()) {
        $db = getDB();
        $stmt = $db->prepare("SELECT theme_name, theme_color FROM users WHERE id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $theme = $stmt->fetch();
        
        if ($theme && $theme['theme_color']) {
            $_SESSION['theme_name'] = $theme['theme_name'];
            $_SESSION['theme_color'] = $theme['theme_color'];
        } else {
            // 设置默认主题
            $_SESSION['theme_name'] = 'sakura';
            $_SESSION['theme_color'] = DEFAULT_THEME_COLOR;
            
            // 保存到数据库
            $stmt = $db->prepare("UPDATE users SET theme_name = ?, theme_color = ? WHERE id = ?");
            $stmt->execute([$_SESSION['theme_name'], $_SESSION['theme_color'], $_SESSION['user_id']]);
        }
    } else {
        // 未登录用户使用默认主题
        if (!isset($_SESSION['theme_color'])) {
            $_SESSION['theme_name'] = 'sakura';
            $_SESSION['theme_color'] = DEFAULT_THEME_COLOR;
        }
    }
}

/**
 * 记录订单操作（修复版本）
 */
function recordOrderOperation($orderId, $operationType, $operationAmount, $operationInfo, $screenshots, $adminId) {
    $db = getDB();
    $stmt = $db->prepare("INSERT INTO order_operations (order_id, operation_type, operation_amount, operation_info, screenshots, admin_id) VALUES (?, ?, ?, ?, ?, ?)");
    
    // 确保screenshots是JSON字符串
    $screenshotsJson = is_array($screenshots) ? json_encode($screenshots) : $screenshots;
    
    return $stmt->execute([
        $orderId, 
        $operationType, 
        $operationAmount, 
        $operationInfo, 
        $screenshotsJson, 
        $adminId
    ]);
}

/**
 * 检查订单是否可以执行操作
 */
function canPerformOperation($order, $operationType) {
    switch ($operationType) {
        case 'register':
            return !$order['is_registered'];
        case 'settle_principal':
        case 'settle_commission':
            return $order['status'] != 'settled';
        case 'return':
            return $order['status'] != 'refunded';
        default:
            return false;
    }
}

/**
 * 创建结算明细记录
 */
function createSettlementDetail($settlementId, $orderId, $settlementType, $settlementAmount, $settlementInfo, $screenshots, $adminId) {
    $db = getDB();
    $stmt = $db->prepare("INSERT INTO settlement_details (settlement_id, order_id, settlement_type, settlement_amount, settlement_info, screenshots, admin_id) VALUES (?, ?, ?, ?, ?, ?, ?)");
    
    $screenshotsJson = is_array($screenshots) ? json_encode($screenshots) : (is_string($screenshots) ? $screenshots : '[]');
    
    return $stmt->execute([
        $settlementId, 
        $orderId, 
        $settlementType, 
        $settlementAmount, 
        $settlementInfo, 
        $screenshotsJson, 
        $adminId
    ]);
}

/**
 * 获取结算明细记录
 */
function getSettlementDetails($settlementId) {
    $db = getDB();
    $stmt = $db->prepare("SELECT sd.*, u.username as admin_name, o.product_name, o.tracking_no, o.order_amount 
                         FROM settlement_details sd 
                         LEFT JOIN users u ON sd.admin_id = u.id 
                         LEFT JOIN orders o ON sd.order_id = o.id 
                         WHERE sd.settlement_id = ? 
                         ORDER BY sd.created_at DESC");
    $stmt->execute([$settlementId]);
    return $stmt->fetchAll();
}

/*
 * 获取订单的最新操作信息
 */
function getOrderLatestOperation($orderId) {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM order_operations WHERE order_id = ? ORDER BY created_at DESC LIMIT 1");
    $stmt->execute([$orderId]);
    return $stmt->fetch();
}
/**
 * 处理订单结算（新版本，支持多次结算记录）
 */
function processOrderSettlementNew($orderId, $settlementType, $settlementAmount, $settlementInfo, $screenshots, $adminId) {
    $db = getDB();
    
    // 获取订单信息
    $stmt = $db->prepare("SELECT user_id, order_amount FROM orders WHERE id = ?");
    $stmt->execute([$orderId]);
    $order = $stmt->fetch();
    
    if (!$order) {
        return false;
    }
    
    $userId = $order['user_id'];
    
    // 计算结算金额
    $finalSettlementAmount = $settlementAmount;
    if (empty($finalSettlementAmount)) {
        if ($settlementType == 'commission') {
            $finalSettlementAmount = $order['order_amount'] * 0.1; // 10%佣金示例
        } else {
            $finalSettlementAmount = $order['order_amount'];
        }
    }
    
    // 检查是否已存在待结算记录
    $pendingSettlement = getUserPendingSettlement($userId);
    
    if ($pendingSettlement) {
        // 更新现有记录
        $existingOrderIds = json_decode($pendingSettlement['order_ids'], true) ?: [];
        if (!in_array($orderId, $existingOrderIds)) {
            $existingOrderIds[] = $orderId;
        }
        $newTotalAmount = $pendingSettlement['total_amount'] + $finalSettlementAmount;
        
        $stmt = $db->prepare("UPDATE settlements SET total_amount = ?, order_ids = ?, updated_at = NOW() WHERE id = ?");
        $updateResult = $stmt->execute([$newTotalAmount, json_encode($existingOrderIds), $pendingSettlement['id']]);
        
        if ($updateResult) {
            // 创建结算明细记录
            return createSettlementDetail($pendingSettlement['id'], $orderId, $settlementType, $finalSettlementAmount, $settlementInfo, $screenshots, $adminId);
        }
    } else {
        // 创建新记录
        $stmt = $db->prepare("INSERT INTO settlements (user_id, settlement_type, total_amount, order_ids, admin_id, status) VALUES (?, ?, ?, ?, ?, 'pending')");
        if ($stmt->execute([$userId, $settlementType, $finalSettlementAmount, json_encode([$orderId]), $adminId])) {
            $settlementId = $db->lastInsertId();
            // 创建结算明细记录
            return createSettlementDetail($settlementId, $orderId, $settlementType, $finalSettlementAmount, $settlementInfo, $screenshots, $adminId);
        }
    }
    
    return false;
}

// 在 functions.php 文件末尾添加以下函数

// ... 原有的 functions.php 代码 ...

/**
 * 生成CSRF令牌
 */
function generateCsrfToken() {
    if (empty($_SESSION['csrf_token']) || time() > ($_SESSION['csrf_token_expire'] ?? 0)) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        $_SESSION['csrf_token_expire'] = time() + CSRF_TOKEN_EXPIRE;
    }
    return $_SESSION['csrf_token'];
}

/**
 * 验证CSRF令牌
 */
function validateCsrfToken($token) {
    if (empty($token) || empty($_SESSION['csrf_token']) || empty($_SESSION['csrf_token_expire'])) {
        return false;
    }
    
    if (time() > $_SESSION['csrf_token_expire']) {
        unset($_SESSION['csrf_token'], $_SESSION['csrf_token_expire']);
        return false;
    }
    
    return hash_equals($_SESSION['csrf_token'], $token);
}

/**
 * 检查登录尝试次数
 */
function checkLoginAttempts($phone) {
    $key = 'login_attempts_' . md5($phone);
    $attempts = $_SESSION[$key] ?? 0;
    $last_attempt = $_SESSION[$key . '_time'] ?? 0;
    
    // 如果超过锁定时间，重置尝试次数
    if (time() - $last_attempt > LOGIN_LOCKOUT_TIME) {
        unset($_SESSION[$key], $_SESSION[$key . '_time']);
        return true;
    }
    
    return $attempts < MAX_LOGIN_ATTEMPTS;
}

/**
 * 记录登录尝试
 */
function recordLoginAttempt($phone) {
    $key = 'login_attempts_' . md5($phone);
    $_SESSION[$key] = ($_SESSION[$key] ?? 0) + 1;
    $_SESSION[$key . '_time'] = time();
}

/**
 * 清除登录尝试记录
 */
function clearLoginAttempts($phone) {
    $key = 'login_attempts_' . md5($phone);
    unset($_SESSION[$key], $_SESSION[$key . '_time']);
}

/**
 * 输入过滤
 */
function sanitizeInput($input) {
    if (is_array($input)) {
        return array_map('sanitizeInput', $input);
    }
    
    $input = trim($input);
    $input = stripslashes($input);
    $input = htmlspecialchars($input, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    
    return $input;
}

/**
 * 验证手机号格式
 */
function validatePhone($phone) {
    return preg_match('/^1[3-9]\d{9}$/', $phone);
}

/**
 * 验证银行卡号
 */
function validateBankCard($cardNumber) {
    // 移除空格和特殊字符
    $cardNumber = preg_replace('/\D/', '', $cardNumber);
    
    // 检查长度（通常16-19位）
    if (strlen($cardNumber) < 16 || strlen($cardNumber) > 24) {
        return false;
    }
    
    // 使用Luhn算法验证
    return luhnCheck($cardNumber);
}

/**
 * Luhn算法验证（用于银行卡号验证）
 */
function luhnCheck($number) {
    $sum = 0;
    $numDigits = strlen($number);
    $parity = $numDigits % 2;
    
    for ($i = 0; $i < $numDigits; $i++) {
        $digit = $number[$i];
        
        if ($i % 2 == $parity) {
            $digit *= 2;
            if ($digit > 9) {
                $digit -= 9;
            }
        }
        
        $sum += $digit;
    }
    
    return ($sum % 10) == 0;
}

/**
 * 记录安全日志
 */
function logSecurityEvent($event, $userId = null, $details = '') {
    $db = getDB();
    $stmt = $db->prepare("INSERT INTO security_logs (user_id, event_type, ip_address, user_agent, details, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
    
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
    
    return $stmt->execute([$userId, $event, $ip, $userAgent, $details]);
}

/**
 * 加密敏感数据
 */
function encryptData($data, $key = null) {
    if ($key === null) {
        $key = DB_PASSWORD; // 使用数据库密码作为加密密钥
    }
    
    $method = 'AES-256-CBC';
    $ivLength = openssl_cipher_iv_length($method);
    $iv = openssl_random_pseudo_bytes($ivLength);
    
    $encrypted = openssl_encrypt($data, $method, $key, 0, $iv);
    return base64_encode($iv . $encrypted);
}

/**
 * 解密敏感数据
 */
function decryptData($data, $key = null) {
    if ($key === null) {
        $key = DB_PASSWORD;
    }
    
    $data = base64_decode($data);
    $method = 'AES-256-CBC';
    $ivLength = openssl_cipher_iv_length($method);
    
    $iv = substr($data, 0, $ivLength);
    $encrypted = substr($data, $ivLength);
    
    return openssl_decrypt($encrypted, $method, $key, 0, $iv);
}

// 在 functions.php 中添加以下函数

/**
 * 获取订单回款状态文本
 */
function getOrderRefundText($isRefunded) {
    return $isRefunded ? '已回款' : '未回款';
}

/**
 * 获取订单回款状态类
 */
function getOrderRefundClass($isRefunded) {
    return $isRefunded ? 'success' : 'secondary';
}

/**
 * 更新订单回款状态
 */
function updateOrderRefundStatus($orderId, $isRefunded, $refundAmount = null, $refundInfo = '', $refundScreenshot = '', $adminId = null) {
    $db = getDB();
    
    $updateFields = [
        'is_refunded' => $isRefunded ? 1 : 0,
        'refunded_at' => $isRefunded ? date('Y-m-d H:i:s') : null,
        'admin_id' => $adminId ?: $_SESSION['user_id'],
        'updated_at' => date('Y-m-d H:i:s')
    ];
    
    if ($refundAmount !== null) {
        $updateFields['refund_amount'] = $refundAmount;
    }
    
    if ($refundInfo) {
        $updateFields['refund_info'] = $refundInfo;
    }
    
    if ($refundScreenshot) {
        $updateFields['refund_screenshot'] = $refundScreenshot;
    }
    
    $setParts = [];
    $params = [];
    foreach ($updateFields as $field => $value) {
        $setParts[] = "{$field} = ?";
        $params[] = $value;
    }
    $params[] = $orderId;
    
    $sql = "UPDATE orders SET " . implode(', ', $setParts) . " WHERE id = ?";
    $stmt = $db->prepare($sql);
    
    return $stmt->execute($params);
}

/**
 * 记录回款操作
 */
function recordRefundOperation($orderId, $refundAmount, $refundInfo, $screenshots, $adminId) {
    return recordOrderOperation($orderId, 'refund', $refundAmount, $refundInfo, $screenshots, $adminId);
}

// 在文件末尾调用初始化函数
initUserTheme();
$settings = settings();